document.addEventListener('DOMContentLoaded', function() {
    const uploadBtn = document.getElementById('upload-btn');
    const fileInput = document.getElementById('avatar-upload');
    const avatarPreview = document.getElementById('avatar-preview');
    const resetBtn = document.getElementById('reset-avatar-btn');
    const defaultAvatar = "https://avrg.oss-cn-hangzhou.aliyuncs.com/avatars/te.jpg";
    const gender=document.getElementById('gender');
    gender.value=genderValue;

    // 点击上传按钮触发文件选择
    uploadBtn.addEventListener('click', function() {
        fileInput.click(); // 触发隐藏的文件input
    });

    // 在文件选择后验证文件类型
    fileInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            const file = e.target.files[0];
            const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

            if (!validTypes.includes(file.type)) {
                alert('请选择有效的图片文件 (JPEG, PNG, GIF, WebP)');
                fileInput.value = '';
                return;
            }

            if (file.size > 5 * 1024 * 1024) { // 5MB
                alert('图片大小不能超过5MB');
                fileInput.value = '';
                return;
            }

            // 预览图片
            const reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('avatar-preview').src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // 重置头像
    resetBtn.addEventListener('click', function() {
        avatarPreview.src = defaultAvatar;
        fileInput.value = '';
    });

    // 添加动画效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(btn => {
        btn.addEventListener('mouseenter', () => {
            btn.style.transform = 'translateY(-2px)';
            btn.style.boxShadow = '0 5px 15px rgba(0,0,0,0.2)';
        });

        btn.addEventListener('mouseleave', () => {
            btn.style.transform = '';
            btn.style.boxShadow = '';
        });
    });
    // 添加表单提交处理
    const userForm = document.getElementById('user-profile-form');
    userForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        try {
            // 1. 如果有新头像文件，先上传到OSS
            let avatarUrl = document.getElementById('avatar-preview').src;
            const fileInput = document.getElementById('avatar-upload');

            if (fileInput.files.length > 0) {
                // 获取OSS上传凭证
                const policyResponse = await fetch(contextPath+'/oss/policy?dir=avatars/');
                const policy = await policyResponse.json();

                // 上传文件到OSS
                avatarUrl = await uploadFileToOss(fileInput.files[0], policy);
            }

            // 2. 收集表单数据（使用上传后的头像URL）
            const formData = {
                userId: userId,
                userName: document.getElementById('username').value,
                password: document.getElementById('password').value,
                gender: parseInt(document.getElementById('gender').value),
                age: parseInt(document.getElementById('age').value),
                phone: document.getElementById('phone').value,
                email: document.getElementById('email').value,
                avatar: avatarUrl
            };

            // 3. 发送AJAX请求保存用户信息
            const saveResponse = await fetch(contextPath+'/User/updateUser', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const data = await saveResponse.json();

            if (data.success) {
                alert(data.message);
                window.location.reload();
            } else {
                alert('保存失败: ' + data.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('操作失败: ' + error.message);
        }

    });

    // 添加取消按钮事件
    document.getElementById('cancel-btn').addEventListener('click', function() {
        if (confirm('确定要放弃修改吗？')) {
            window.location.reload(); // 重新加载页面放弃修改
        }
    });
});
document.addEventListener('DOMContentLoaded', function() {
    const uploadBtn = document.getElementById('upload-btn');
    const fileInput = document.getElementById('avatar-upload');
    const avatarPreview = document.getElementById('avatar-preview');
    const resetBtn = document.getElementById('reset-avatar-btn');
    const defaultAvatar = "https://avrg.oss-cn-hangzhou.aliyuncs.com/avatars/te.jpg";
    const gender=document.getElementById('gender');
    gender.value=genderValue;

    // 点击上传按钮触发文件选择
    uploadBtn.addEventListener('click', function() {
        fileInput.click(); // 触发隐藏的文件input
    });

    // 在文件选择后验证文件类型
    fileInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            const file = e.target.files[0];
            const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

            if (!validTypes.includes(file.type)) {
                alert('请选择有效的图片文件 (JPEG, PNG, GIF, WebP)');
                fileInput.value = '';
                return;
            }

            if (file.size > 5 * 1024 * 1024) { // 5MB
                alert('图片大小不能超过5MB');
                fileInput.value = '';
                return;
            }

            // 预览图片
            const reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('avatar-preview').src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // 重置头像
    resetBtn.addEventListener('click', function() {
        avatarPreview.src = defaultAvatar;
        fileInput.value = '';
    });

    // 添加动画效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(btn => {
        btn.addEventListener('mouseenter', () => {
            btn.style.transform = 'translateY(-2px)';
            btn.style.boxShadow = '0 5px 15px rgba(0,0,0,0.2)';
        });

        btn.addEventListener('mouseleave', () => {
            btn.style.transform = '';
            btn.style.boxShadow = '';
        });
    });
    // 添加表单提交处理
    const userForm = document.getElementById('user-profile-form');
    userForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        try {
            // 1. 如果有新头像文件，先上传到OSS
            let avatarUrl = document.getElementById('avatar-preview').src;
            const fileInput = document.getElementById('avatar-upload');

            if (fileInput.files.length > 0) {
                // 获取OSS上传凭证
                const policyResponse = await fetch(contextPath+'/oss/policy?dir=avatars/');
                const policy = await policyResponse.json();

                // 上传文件到OSS
                avatarUrl = await uploadFileToOss(fileInput.files[0], policy);
            }

            // 2. 收集表单数据（使用上传后的头像URL）
            const formData = {
                userId: userId,
                userName: document.getElementById('username').value,
                password: document.getElementById('password').value,
                gender: parseInt(document.getElementById('gender').value),
                age: parseInt(document.getElementById('age').value),
                phone: document.getElementById('phone').value,
                email: document.getElementById('email').value,
                avatar: avatarUrl
            };

            // 3. 发送AJAX请求保存用户信息
            const saveResponse = await fetch(contextPath+'/User/updateUser', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const data = await saveResponse.json();

            if (data.success) {
                alert(data.message);
                window.location.reload();
            } else {
                alert('保存失败: ' + data.message);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('操作失败: ' + error.message);
        }

    });

    // 添加取消按钮事件
    document.getElementById('cancel-btn').addEventListener('click', function() {
        if (confirm('确定要放弃修改吗？')) {
            window.location.reload(); // 重新加载页面放弃修改
        }
    });
});